package com.sxj.shop.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 石小俊
 * @date 2024年03月20日 19:10
 */
//@WebFilter(urlPatterns = "/*", initParams = {
//        @WebInitParam(name = "blackList", value = "192.168.56.1")
//})
public class BlackListFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取访问者的ip地址
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String ip = request.getRemoteAddr();
        String blackList = config.getInitParameter("blackList");
        String[] arr = blackList.split(",");
        for(String s : arr){
            if (ip.equals(s)) {
                PrintWriter out = response.getWriter();
                out.print("<h1 style='color:red;'>对不起,您是黑名单用户,无法访问!");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
